import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.util.Scanner;

public class FileClient {

    //套接字声明
    private Socket socket1 = null;

    public static void main(String[] args) throws IOException {
        FileClient fileClient = new FileClient("127.0.0.1",2021);
        fileClient.start();
    }

    public FileClient(String serverIp,int port1) throws IOException {
        socket1 = new Socket(serverIp,port1);
    }

    //服务器端运行函数
    public void start(){
        System.out.println("客户端启动！");
        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
             PrintWriter out = new PrintWriter(socket1.getOutputStream(), true);
             Scanner scanner = new Scanner(System.in)){

            //服务器端返回指令
            String response;
            //等待连接
            while ((response = in.readLine()) != null) {
                System.out.println(response);
                if (response.contains("连接成功")) {
                    break;
                }
            }

            //对客户输入的指令进行响应，并发送给服务器端
            while (true){
                System.out.print("请输入指令'ls','cd',’get <file>‘,'bye': ");
                String command = scanner.nextLine();
                out.println(command);

                if (command.equals("bye")) {
                    break;
                } else if (command.contains("get")) {
                    receiveFile(socket1);

                } else {
                    //对服务器的返回进行响应
                    while ((response = in.readLine()) != null && !response.isEmpty()) {
                        System.out.println(response);
                        if(response.contains("successfully change")||response.contains("无法加载，请检查指令是否正确")||
                                response.contains("Directory does not exist.")||response.contains("请输入正确指令!")||
                                response.contains("Cannot change to the parent directory.")){
                            break;
                        }
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //接收文件函数
    private static void receiveFile(Socket socket) {
        BufferedReader in;
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 从服务器接收响应
            String command = in.readLine();
            String[] parts = command.split(" ");
            //当服务器返回发送失败时直接退出
            for(String s:parts)
                System.out.println(s);
            if (parts.length != 3 || !parts[0].equals("OK")) {
                System.out.println("Invalid response for 'get' command.");
                return;
            }

            //在指定目录创建文件
            String fileName = parts[1];
            String filepath ="E:\\test\\";
            long fileSize = Long.parseLong(parts[2]);

            //开始接收文件
            try (FileOutputStream fileOutput = new FileOutputStream(filepath +fileName);
                 DatagramSocket udpSocket = new DatagramSocket(2020)) {

                byte[] buffer = new byte[1024];
                long totalBytesReceived = 0;
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                //当准备工作完毕时向服务器发送信号表示可以开始传送
                out.println("准备接收");

                //利用udp进行文件传送与接收工作
                while (totalBytesReceived < fileSize) {
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                    udpSocket.receive(packet);
                    fileOutput.write(packet.getData(), 0, packet.getLength());
                    totalBytesReceived += packet.getLength();
                }
                System.out.println("Received " + totalBytesReceived + " bytes via UDP.");
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (IOException e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        }
    }
}